/*
 Script: GearsORM.js
 Contains the main namespace for GearsORM and a thin abstraction for open,close and execute functions
 
 License:
 MIT-style license.
 */
/*
 Class: GearsORM
 the main namespace for GearsORM,also provide a basic api wrapper for execute,close and open
 */
var GearsORM = {
    version: "0.2.1",
    _db: null,
    _models: {},
    dbName: "gears.orm",
    debug: true,
    /*
     Function: getDB
     return a open database connection
     
     Returns:
     A open database connection.
     */
    getDB: function(){
        if (!GearsORM._db) {
            try {
                GearsORM._db = google.gears.factory.create('beta.database', '1.0');
                GearsORM._db.open(GearsORM.dbName);
            } 
            catch (e) {
                throw new Error("couldn`t open database: " + GearsORM.dbName + " exception: " + e.message);
            }
        }
        return GearsORM._db;
    },
    /*
     Function: execute
     execute a sql query on the database
     
     Parameters:
     sql - sql query to execute
     params - bind parameters to be used in the sql query,optional
     */
    execute: function(sql, params){
        try {
            if (GearsORM.debug) 
                GearsORM.log(sql, params);
            return GearsORM.getDB().execute(sql, params || []);
        } 
        catch (e) {
            throw new Error(e.message);
        }
    },
    /*
     Function: executeAndClose
     execute a sql query on the database and close it.
     
     Parameters:
     sql - sql query to execute
     params - bind parameters to be used in the sql query,optional
     */
    executeAndClose: function(sql, params){
        try {
            var rs = GearsORM.execute(sql, params);
            rs.close();
            return rs;
        } 
        catch (e) {
            throw new Error(e.message);
        }
    },
    /*
     Function: close
     close the database connection.
     */
    close: function(){
        GearsORM.getDb().close();
    },
    /*
     taken from mootools
     */
    extend: function(src, add){
        if (!add) {
            add = src;
            src = this;
        }
        for (var property in add) 
            src[property] = add[property];
        return src;
    }
};
if (window.console && window.console.log && GearsORM.debug) 
    GearsORM.log = console.log;
else 
    GearsORM.log = function(){
    };
